//
//  ZLPhotoBrowserViewController.m
//  XiangJi
//
//  Created by apple on 2017/8/8.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "ZLPhotoBrowserViewController.h"
#import <ZLPhotoActionSheet.h>
#import <ZLPhotoManager.h>
#import <ToastUtils.h>
#import <ZLProgressHUD.h>
@interface ZLPhotoBrowserViewController ()<NSURLSessionDownloadDelegate, UIScrollViewDelegate>{
    
    ZLPhotoActionSheet *actionSheet;
}

@property (nonatomic, strong) UIButton *btn;

@property (nonatomic, strong) UIButton *saveBtn;

@property (nonatomic, strong) UIImageView *imagV;;

@property (nonatomic, strong) UIImage *img;

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) UIButton *addBtn;

@property (nonatomic, strong) UIImageView *imagScrollV;;

@property (nonatomic, strong) NSMutableArray *scrolMutArr;


@end

@implementation ZLPhotoBrowserViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.btn = [[UIButton alloc] initWithFrame:CGRectMake(100, 400, 100, 50)];
    
    [self.btn setTitle:@"Login" forState:UIControlStateNormal];
    
    [self.btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    
    [self.btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_btn];
    
    self.saveBtn = [[UIButton alloc] initWithFrame:CGRectMake(100, 500, 100, 50)];
    
    [self.saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    
    [self.saveBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    
    [self.saveBtn addTarget:self action:@selector(saveBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_saveBtn];
    
    
    self.imagV = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
    
    self.imagV.backgroundColor = [UIColor blueColor];
    
    [self.view addSubview:_imagV];
    
    /**************我***************是****************分****************割***************线****************/
    
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 250, 100, 100)];
    
    self.scrollView.delegate = self;
    
    //    self.scrollView.contentSize = CGSizeMake(6*100, 100);
    
    //    self.scrollView.contentOffset = CGPointMake(0, 0);
    
    self.scrollView.contentMode = UIViewContentModeScaleAspectFill;
    
    self.scrollView.backgroundColor = [UIColor orangeColor];
    
    self.scrollView.bounces = NO;
    
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.pagingEnabled = YES;//分页
    
    [self.view addSubview:self.scrollView];
    
    
    self.addBtn = [UIButton buttonWithType:UIButtonTypeContactAdd];
    
    self.addBtn.frame = CGRectMake(110, 250, 100, 100);
    
    [self.addBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    
    [self.addBtn addTarget:self action:@selector(addBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_addBtn];
    
    self.scrolMutArr = [NSMutableArray arrayWithCapacity:0];
    
    
    /**************我***************是****************分****************割***************线****************/
    
    
    NSString *strImgPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    
    NSString *strImg = [strImgPath stringByAppendingString:@"/123.jpg"];
    
    NSFileManager *file = [NSFileManager defaultManager];
    
    if ([file fileExistsAtPath:strImg]) {
        
        self.imagV.image = [UIImage imageWithContentsOfFile:strImg];
        
    }else{
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
            
            NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://img06.tooopen.com/images/20170514/tooopen_sy_210122159348.jpg"]]];
            
            [task resume];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
            });
        });
    }
    
    
    ZLProgressHUD *p = [[ZLProgressHUD alloc] init];
    
    [p show];
}


- (void)addBtnClick{
    
    actionSheet = [[ZLPhotoActionSheet alloc] init];
    //设置照片最大预览数
    actionSheet.maxPreviewCount = 20;
    //设置照片最大选择数
    actionSheet.maxSelectCount = 10;
    actionSheet.sender = self;
    
    __weak typeof(self)weakSelf = self;
    //选择图片方法调用
    [actionSheet setSelectImageBlock:^(NSArray<UIImage *> * _Nonnull images, NSArray<PHAsset *> * _Nonnull assets, BOOL isOriginal) {
        //your codes
        
        weakSelf.imagV.image = images[0];
        
//        weakSelf.scrolMutArr = [NSMutableArray arrayWithArray:images];
        
        weakSelf.scrollView.contentSize = CGSizeMake(images.count*100, 100);
        
        for (int i = 0; i < images.count; i++) {
            
            weakSelf.imagScrollV = [[UIImageView alloc] init];
            
            weakSelf.imagScrollV.backgroundColor = [UIColor blueColor];
            
            weakSelf.imagScrollV.frame = CGRectMake(i * 100, 0, 100, 100);
            
            weakSelf.imagScrollV.userInteractionEnabled = YES;
            
            weakSelf.imagScrollV.image = images[i];
            
            weakSelf.imagScrollV.tag = i;
            
            [weakSelf.scrollView addSubview:weakSelf.imagScrollV];
            
            [weakSelf.scrolMutArr addObject:[NSString stringWithFormat:@"%d",i]];
//            [weakSelf.scrolMutArr addObject:weakSelf.imagScrollV];
            
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:weakSelf action:@selector(tapClick:)];
            
            tap.numberOfTapsRequired = 2;
            
            [weakSelf.imagScrollV addGestureRecognizer:tap];
        }
        
    }];
    
//    [actionSheet showPreviewAnimated:YES]; //有alertSheet弹出框
        [actionSheet showPhotoLibrary];  //直接进入相册
    
//    [actionSheet showCamera];
    
}

- (void)tapClick:(UITapGestureRecognizer *)sender{
    
    /**************我***************是****************分****************割***************线****************/
    //每次删除最后一个完全没问题
    
    long int l = sender.view.tag;
    
    NSLog(@"l = %ld",l);

    
    
    NSLog(@"1 = %@",_scrolMutArr);
    
    [self.scrolMutArr removeObject:[NSString stringWithFormat:@"%ld",l]];
    
    [self.scrolMutArr addObject:[NSString stringWithFormat:@"%ld",l]];
    
  
    
    NSLog(@"2 = %@",_scrolMutArr);
    
        long int tmp = [self.scrolMutArr.lastObject intValue];
    
        UIImageView *imV = (UIImageView *)[self.scrollView.subviews lastObject];
    
    imV.frame = CGRectMake(self.scrollView.subviews.count *100, 0, 100, 100);
    
        [imV removeFromSuperview];
        
        self.scrollView.contentSize = CGSizeMake(self.scrollView.subviews.count *100, 100);

    NSLog(@"count = %ld",self.scrollView.subviews.count);
    
    [self.scrolMutArr removeObject:[NSString stringWithFormat:@"%ld",l]];
    
    if (!l) {
        
        for (int i = 0; i < self.scrolMutArr.count; i++) {
            
            long int k = [self.scrolMutArr[i] intValue];
            
            UIImageView *lImgV = (UIImageView *)self.scrollView.subviews[k];
            
            lImgV.tag = i;
            
            lImgV.frame = CGRectMake(i*100, 0, 100, 100);
        }
    }

    /**************我***************是****************分****************割***************线****************/
    
}

- (void)btnClick{
    
    [self tanChu];
}

/**
 保存按钮点击保存图片到系统相册
 */
- (void)saveBtnClick{
    
    //类方法保存图片
    [ZLPhotoManager saveImageToAblum:self.imagV.image completion:^(BOOL suc, PHAsset *asset) {
        
        NSLog(@"--= %d",suc);
        
    }];
    
    [ToastUtils showLongAtTop:@"已经保存啦！！！"];
}


/**
 点击login按钮进入相册
 */
- (void)tanChu{
    
    actionSheet = [[ZLPhotoActionSheet alloc] init];
    //设置照片最大预览数
    actionSheet.maxPreviewCount = 20;
    //设置照片最大选择数
    actionSheet.maxSelectCount = 10;
    actionSheet.sender = self;
    
    
    __weak typeof(self)weakSelf = self;
    //选择图片方法调用
//    [actionSheet setSelectImageBlock:^(NSArray<UIImage *> * _Nonnull images, NSArray<PHAsset *> * _Nonnull assets, BOOL isOriginal) {
//        //your codes
//        
//        weakSelf.imagV.image = images[0];
//    }];
    
    [actionSheet setSelectImageBlock:^(NSArray<UIImage *> * _Nonnull images, NSArray<PHAsset *> * _Nonnull assets, BOOL isOriginal) {
        //your codes
        
        weakSelf.imagV.image = images[0];
    }];
    
    //        [actionSheet showPreviewAnimated:YES]; //有alertSheet弹出框
//    [actionSheet showPhotoLibrary];  //直接进入相册
    
    [actionSheet showCamera];
}


/**
 下载任务完成进入此方法
 
 @param session session
 @param downloadTask task
 @param location 地址
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    
    NSString *strPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    
    NSString *str = [strPath stringByAppendingString:@"/123.jpg"];
    
    NSLog(@"str = %@",str);
    
    //移动下载的图片进入一个新的地址，且名字为123.jpg
    [[NSFileManager defaultManager] moveItemAtPath:location.path toPath:str error:nil];
    
    self.imagV.image = [UIImage imageWithContentsOfFile:str];//加载图片
}

@end
